set more off
clear all
cap log close
cd "~/Dropbox/Farm Subsidies and Committees/analyses/local_reg"


foreach switch in all lfp dcp {
	use if !missing(election_year_desc) & election_year_desc >= 2009 using ../collapsed, clear
	* drop if missing(election_year_desc)
	* keep if election_year_desc >= 2009

	* drop orgs
	merge m:1 customer_code using ../org_ids, keep(1) nogen

	preserve
	keep if ran == 1
	collapse (mean) woncondran_avg=winner (max) woncondran_max=winner, by(customer_code)
	replace woncondran_avg = 100*woncondran_avg
	replace woncondran_max = 100*woncondran_max
	gen condran = 1

	tempfile woncondran
	save `woncondran', replace
	restore


	* rescale vars
	replace voted = 100*voted
	replace ran = 100*ran
	replace winner = 100*winner


	* pooled across years
	collapse (mean) voted_avg=voted ran_avg=ran won_avg=winner amt_avg=amt_`switch' (max) voted_max=voted ran_max=ran won_max=winner, by(customer_code)
	label var voted_avg "Voted (average across years)"
	label var ran_avg "Ran (average across years)"
	label var won_avg "Won (average across years)"
	label var voted_max "Voted (max across years)"
	label var ran_max "Ran (max across years)"
	label var won_max "Won (max across years)"
	label var amt_avg "Amt. (average across years)"


	* merge in condran
	merge 1:1 customer_code using `woncondran', nogen
	label var condran "indicator for id in woncondran data"


	* winsorize amt 1-99
	egen amt_avg_p1 = pctile(amt_avg), p(1)
	egen amt_avg_p99 = pctile(amt_avg), p(99)
	gen amt_avg_wsz = amt_avg
	replace amt_avg_wsz = amt_avg_p1 if amt_avg_wsz < amt_avg_p1
	replace amt_avg_wsz = amt_avg_p99 if amt_avg_wsz > amt_avg_p99
	label var amt_avg_wsz "Winsorized amt_avg at 1 and 99 pctiles"


	* gen quantiles and tables
	fastxtile amt_avg_q20 = amt_avg, nq(20)
	fastxtile amt_avg_q50 = amt_avg, nq(50)
	fastxtile amt_avg_wsz_q20 = amt_avg_wsz, nq(20)
	fastxtile amt_avg_wsz_q50 = amt_avg_wsz, nq(50)


	compress
	save local_reg_`switch', replace


	log using qtile_table_`switch'.txt, text replace

	foreach qvar in amt_avg_q20 amt_avg_q50 amt_avg_wsz_q20 amt_avg_wsz_q50 {
		di ""
		di "----------------- START `qvar' START-----------------"
		table `qvar', c(mean voted_avg mean ran_avg mean won_avg)
		table `qvar', c(mean voted_max mean ran_max mean won_max)
		table `qvar', c(median amt_avg min amt_avg max amt_avg sd amt_avg)
		di "----------------- END `qvar' END-----------------"
		di ""
	}


	foreach qvar in amt_avg_q20 amt_avg_q50 {
		di ""
		di "----------------- START `qvar', within 1-99 pctile START -----------------"
		table `qvar' if inrange(amt_avg, amt_avg_p1, amt_avg_p99), c(mean voted_avg mean ran_avg mean won_avg)
		table `qvar' if inrange(amt_avg, amt_avg_p1, amt_avg_p99), c(mean voted_max mean ran_max mean won_max)
		table `qvar' if inrange(amt_avg, amt_avg_p1, amt_avg_p99), c(median amt_avg min amt_avg max amt_avg sd amt_avg)
		di "----------------- END `qvar', within 1-99 pctile END -----------------"
		di ""
	}

	log close

}
